package again.newlife.jackson;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JacksonTest02 {

    public static void main(String[] args) throws IOException {
        //准备集合
        List<User> list = new ArrayList<>();
        list.add(new User(1, "张三", "北京"));
        list.add(new User(2, "王五", "上海"));
        list.add(new User(3, "赵六", "广州"));
        list.add(new User(4, "孙七", "深圳"));
        list.add(new User(5, "周八", "杭州"));

        // 创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();

        // 1.将list集合对象转为：json字符串
        String s = mapper.writeValueAsString(list);
        System.out.println("json字符串" + s);
        // 2.将list集合对象转为：json字符串，并存入day14-code/src/again/newlife/file/jacksonlist.json文件中
        mapper.writeValue(new File("day14-code/src/again/newlife/file/jacksonlist.json"), list);
        // 3.将list集合对象转为：字节数组
        byte[] bytes = mapper.writeValueAsBytes(list);
        System.out.println("字节数组" + new String(bytes));
        // 4.将list集合对象的json字符串转为list集合对象
        JsonNode jsonNode = mapper.readTree(s);
        for (JsonNode node : jsonNode) {
            System.out.println(node);
        }
        System.out.println("-----------------------------------");

        // 5.将jacksonlist.json文件中的list集合json字符串读出来，并转为list集合对象
        JsonNode jsonNode1 = mapper.readTree(new File("day14-code/src/again/newlife/file/jacksonlist.json"));
        for (JsonNode node : jsonNode1) {
            System.out.println(node);
        }
        System.out.println("-----------------------------------");

        //6. 将bytes数组中的内容转为对象
        JsonNode jsonNode2 = mapper.readTree(bytes);
        for (JsonNode node : jsonNode2) {
            System.out.println(node);
        }
    }
}
